﻿using System.Collections;
using System.Collections.Generic;
using GameFramework.Localization;
using GameFramework.Procedure;
using UnityEngine;
using UnityGameFramework.Runtime;
using ProcedureOwner = GameFramework.Fsm.IFsm<GameFramework.Procedure.IProcedureManager>;
using AppsFlyerSDK;
using Facebook.Unity;
using UPTrace;

namespace TowerDefence_Zombie
{
    public class ProcedureLaunch : ProcedureBase
    {
        private const string PRODUCTID = "AOS:600431";

        private const string CHANNELID = "32400";

        private const string AF_DEV_KEY = "fZvuk792H9hJQKmaTwuXxA";

        private bool inited;

        private bool initComplete;

        protected override void OnEnter(ProcedureOwner procedureOwner)
        {
            // 构建信息：发布版本时，把一些数据以 Json 的格式写入 Assets/GameMain/Configs/BuildInfo.txt，供游戏逻辑读取
            GameEntry.BuiltinData.InitBuildInfo();

            InitSDK();

            // 语言配置：设置当前使用的语言，如果不设置，则默认使用操作系统语言。
            InitLanguageSettings();

            // 变体配置：根据使用的语言，通知底层加载对应的资源变体
            InitCurrentVariant();

            // 默认字典：加载默认字典文件 Assets/GameMain/Configs/Default
            // 此字典文件记录了资源更新前使用的各种语言的字符串，会随 App 一起发布，故不可更新
            GameEntry.BuiltinData.InitDefaultDictionary();

            base.OnEnter(procedureOwner);
        }

        protected override void OnUpdate(ProcedureOwner procedureOwner, float elapseSeconds, float realElapseSeconds)
        {
            base.OnUpdate(procedureOwner, elapseSeconds, realElapseSeconds);

            if (GetSDKIsReady())
                ChangeState<ProcedureSplash>(procedureOwner);
        }

        private void InitLanguageSettings()
        {
            if (GameEntry.Base.EditorResourceMode && GameEntry.Base.EditorLanguage != Language.Unspecified)
            {
                // 编辑器资源模式直接使用 Inspector 上设置的语言
                GameEntry.Setting.SetInt(Constant.Setting.Language, (int)GameEntry.Base.EditorLanguage);
                GameEntry.Setting.Save();
                return;
            }

            Language language = (Language)GameEntry.Setting.GetInt(Constant.Setting.Language, (int)Language.English);

            if (language != Language.English
                && language != Language.ChineseSimplified
                && language != Language.ChineseTraditional)
            {
                // 若是暂不支持的语言，则使用英语
                language = Language.English;

                GameEntry.Setting.SetString(Constant.Setting.Language, language.ToString());
                GameEntry.Setting.Save();
            }

            GameEntry.Localization.Language = language;

            Log.Info("Init language settings complete, current language is '{0}'.", language.ToString());
        }

        private void InitCurrentVariant()
        {
            if (GameEntry.Base.EditorResourceMode)
            {
                // 编辑器资源模式不使用 AssetBundle，也就没有变体了
                return;
            }

            string currentVariant = null;
            switch (GameEntry.Localization.Language)
            {
                case Language.English:
                    currentVariant = "en-us";
                    break;

                case Language.ChineseSimplified:
                    currentVariant = "zh-cn";
                    break;

                case Language.ChineseTraditional:
                    currentVariant = "zh-tw";
                    break;

                default:
                    currentVariant = "en-us";
                    break;
            }

            GameEntry.Resource.SetCurrentVariant(currentVariant);
            Log.Info("Init current variant complete.current variant :{0}.", currentVariant);
        }

        private void InitSDK()
        {
            if (inited)
            {
                return;
            }
            inited = true;

            var baseComponent = UnityGameFramework.Runtime.GameEntry.GetComponent<BaseComponent>();
            baseComponent.StartCoroutine(SDKFlowProcesser());
        }

        private IEnumerator SDKFlowProcesser()
        {
            FB.Init(() => FB.ActivateApp());

            var baseComponent = UnityGameFramework.Runtime.GameEntry.GetComponent<BaseComponent>();
            var afObj = Resources.Load<AppsFlyerObjectScript>("Prefabs/SDK/AppsFlyerObject");
            UnityEngine.Object.Instantiate(afObj, baseComponent.transform.parent);
            yield return new WaitUntil(() =>
            {
                if (AppsFlyer.instance == null)
                {
                    return false;
                }
                return AppsFlyer.instance.isInit;
            });

            Debug.Log($"AppsFlyer sendEvent af_open");
            AppsFlyer.sendEvent("af_open", new Dictionary<string, string>());

            Debug.Log($"AppsFlyer sendEvent af_login");
            AppsFlyer.sendEvent("af_login", new Dictionary<string, string>());

            UPTraceApi.enalbeDebugMode(true);
            UPTraceApi.initTraceSDKWithCallback(PRODUCTID, CHANNELID, initSuccessCallback, initFailCallback);
#if UNITY_EDITOR 
            initComplete = true;
#endif
        }

        public void initSuccessCallback(string msg)
        {
            Debug.Log($"tasdk initSuccessCallback {msg}");

            string afid = AppsFlyer.getAppsFlyerId();
            if (string.IsNullOrEmpty(afid) == false)
            {
                Debug.Log($"setAFId {afid}");

                UPTraceApi.setAFId(afid);
            }
            Debug.Log($"AppsFlyer setCustomerUserId {UPTraceApi.getOpenId()}");
            AppsFlyer.setCustomerUserId(UPTraceApi.getOpenId());

            Debug.Log($"UPTraceApi guestLogin {UPTraceApi.getUserId()}");
            UPTraceApi.guestLogin(UPTraceApi.getUserId());

            Debug.Log($"UPTraceApi traceKey T01");
            UPTraceApi.traceKey("T01");

            Dictionary<string, string> dic = new()
            {
                { "I", "guest" },
            };
            Debug.Log($"UPTraceApi traceDictionary T03");
            UPTraceApi.traceDictionary("T03", dic);

            Debug.Log($"UPTraceApi initDurationReport");
            UPTraceApi.initDurationReport("", "", UPTraceApi.getUserId(), UPTraceApi.getUserId());

            initComplete = true;
        }

        public void initFailCallback(string message)
        {
            initComplete = true;
            Debug.Log("tasdk initFailCallback ,message =" + message);
        }

        private bool GetSDKIsReady() => FB.IsInitialized && initComplete;
    }
}

